﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Management;
using System.Web.Routing;

namespace DNA.Mvc.Management
{
    public class WebRequestTraceModule : IHttpModule
    {
        public void Dispose() { }

        public void Init(HttpApplication context)
        {
            context.AuthenticateRequest += new EventHandler(context_BeginRequest);
        }

        private bool ShouldLog(HttpRequestBase request)
        {
            if (request.IsAjaxRequest())
                return false;

            if (!(request.HttpMethod.Equals("GET",StringComparison.OrdinalIgnoreCase)))
                return false;

            var uri = request.Url;
            var routeValues = new RouteValueDictionary();

            if ((request.RequestContext != null) && (request.RequestContext.RouteData != null) && (request.RequestContext.RouteData.Values != null))
                routeValues = request.RequestContext.RouteData.Values;

            if ((request.AcceptTypes != null) && (request.AcceptTypes.Count() > 0))
            {
                var accepts = request.AcceptTypes[0];
                if (!string.IsNullOrEmpty(accepts))
                {
                    if ((accepts.StartsWith("image", StringComparison.OrdinalIgnoreCase)) || accepts.Equals("text/css", StringComparison.OrdinalIgnoreCase))
                        return false;

                    if (!string.IsNullOrEmpty(request.AppRelativeCurrentExecutionFilePath) &&
                        (request.AppRelativeCurrentExecutionFilePath.EndsWith(".js") ||
                        (request.AppRelativeCurrentExecutionFilePath.EndsWith(".vbs"))))
                        return false;
                }
            }

            var ext = "";

            try
            {
                if (uri.IsFile)
                    ext = System.IO.Path.GetExtension(uri.LocalPath);
            }
            catch { return false; }

            //Static files.
            if (!string.IsNullOrEmpty(ext) && ((routeValues == null) || (routeValues.Values.Count == 0)))
                return false;

            //Ignore files.
            if (routeValues.ContainsKey("controller") && routeValues["controller"].ToString().Equals("WebFiles", StringComparison.OrdinalIgnoreCase))
                return false;

            return true;
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            var httpApp = sender as HttpApplication;
            var httpContext = httpApp.Context;

            if (httpContext != null)
            {
                try
                {

                    var request = new HttpRequestWrapper(httpContext.Request);

                    if (ShouldLog(request))
                    {
                        var eventCode = WebEventCodes.WebExtendedBase + 10;
                        var requestEvent = new ExplicitilyWebRequestEvent("Web request start", this, eventCode);
                        requestEvent.Request = request;
                        requestEvent.UserHostName = request.UserHostName;
                        requestEvent.UserHostAddress = requestEvent.UserHostAddress;

                        // Raise the event.
                        requestEvent.Raise();
                    }
                }
                catch (Exception ex)
                {
                    var eee = ex;
                }
            }
        }
    }
}
